package com.yunshipei.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.fsck.k9.activity.MessageCompose;
import com.yunshipei.adapter.Search_sortAdapter;
import com.yunshipei.base.BaseActivity;
import com.yunshipei.common.PinyinComparator;
import com.yunshipei.common.wedigt.YspTitleBar;
import com.yunshipei.db.DatabaseUtil;
import com.yunshipei.common.Globals;
import com.yunshipei.model.UserInfo;
import com.yunshipei.enterplorer.R;
import com.yunshipei.model.ShareInfoModel;
import com.yunshipei.model.ShareItemEnum;
import com.yunshipei.model.ShareModel;
import com.yunshipei.model.SortModel;
import com.yunshipei.ui.view.SideBar;
import com.yunshipei.ui.view.SideBar.OnTouchingLetterChangedListener;
import com.yunshipei.utils.CharacterParser;
import com.yunshipei.utils.ClearEditText;
import com.yunshipei.utils.ShareUtil;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import io.rong.app.activity.GroupMainPageActivity;
import io.rong.imkit.mention.RongMentionManager;
import io.rong.imlib.model.Conversation;

public class SeekContactsActivity extends BaseActivity implements ShareUtil.OnSendMessageSuccessListener {

    private ListView sortListView;
    private SideBar sideBar;
    private TextView dialog;
    private Search_sortAdapter adapter;
    private ClearEditText mClearEditText;
    private DatabaseUtil dbUtil;
    private SharedPreferences mySharedPreferences;
    private List<UserInfo> list;
    private boolean status = true;
    private List<SortModel> sortedList;
    public static final String EMAIL_ADDRESS_EXTRA = "email_address";
    public static final String EMAIL_NAME_EXTRA = "email_name";
    public static final String EMAIL_FIRST_ITEM = "email_first_select_item";
    private int firstItemPosition = 0;
    private YspTitleBar mTitleBar;
    private CharacterParser characterParser;
    private List<SortModel> SourceDateList;
    private PinyinComparator pinyinComparator;
    private String action =null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.seek_contacts);
        initView();
        initData();
    }

    public void initView() {
        action = getIntent().getAction();
        sortedList = new ArrayList<SortModel>();
        mTitleBar = (YspTitleBar) findViewById(R.id.title_bar);
        mTitleBar.setTitle("搜索");
        list = new ArrayList<UserInfo>();
        dbUtil = new DatabaseUtil();
        list = dbUtil.queryAll();
        list = removeUserIsAdmin(list);
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        sideBar = (SideBar) findViewById(R.id.sidrbar);
        dialog = (TextView) findViewById(R.id.dialog);
        sideBar.setTextView(dialog);
        sortListView = (ListView) findViewById(R.id.country_lvcountry);
        SourceDateList = new ArrayList<SortModel>();
        SourceDateList = filledData(list);
        // 根据a-z进行排序源数据
        Collections.sort(SourceDateList, pinyinComparator);
        adapter = new Search_sortAdapter(this, SourceDateList);
        sortListView.setAdapter(adapter);
        int temp = getIntent().getIntExtra(MessageCompose.EXTRA_CONTACTS_FIRST_POS, 0);
        sortListView.setSelection(temp);
        mClearEditText = (ClearEditText) findViewById(R.id.filter_edit);
        mClearEditText.clearFocus();
    }

    private void initData() {
        mySharedPreferences = getApplication().getSharedPreferences("ysp_rongCloud", Activity.MODE_PRIVATE);
        sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);
                }
            }
        });
        mClearEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                SearchTask searchTask = new SearchTask();
                searchTask.execute(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        initAllGroup();         //所有群成员
        initAt();               //@选择人
        initSendMail();         //发送文件
        initShare();            //初始化分享
        if (TextUtils.isEmpty(action)) {
            listItemClick();
        }
    }

    /**
     * 初始化分享
     */
    private void initShare() {
        if (Globals.SHARE.equals(action)) {
            sortListView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    SortModel sortModel = (SortModel) parent.getAdapter().getItem(position);
                    Bundle bundle = getIntent().getBundleExtra("shareInfoModel");
                    ShareInfoModel shareInfoModel = (ShareInfoModel) bundle.getSerializable("shareInfoModel");
                    ShareModel shareModel = new ShareModel();
                    shareModel.setItemType(ShareItemEnum.CONTACT);
                    shareModel.setName(sortModel.getUserInfo().getName());
                    shareModel.setAvator(sortModel.getUserInfo().getAvatar());
                    shareModel.setTargetId(sortModel.getUserInfo().getUuid());
                    shareModel.setNember(0);
                    shareInfoModel.setType(Conversation.ConversationType.PRIVATE);
                    shareInfoModel.setShareModel(shareModel);
                    ShareUtil shareUtil = new ShareUtil(SeekContactsActivity.this);
                    shareUtil.setData(shareInfoModel);
                    shareUtil.setOnDefineClickLisenter(SeekContactsActivity.this);
                    shareUtil.showDialog();
                }
            });
            return;
        }
    }

    /**
     * 初始化@
     */
    private void initAt() {
        if (Globals.AT.equals(action)) {
            mTitleBar.setGoBackVisible(View.VISIBLE);
            String groupMembers = getIntent().getStringExtra("groupMembers");
            if (!TextUtils.isEmpty(groupMembers)) {
                list = getAvatarList(groupMembers);
                sortedList = filledData(list);
                Collections.sort(sortedList, pinyinComparator);
                adapter.updateListView(sortedList);
            }
            sortListView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (!sortedList.get(position).getUserInfo().getUuid().equals(mySharedPreferences.getString("uuid", ""))) {
                        io.rong.imlib.model.UserInfo userInfo = new io.rong.imlib.model.UserInfo(sortedList.get(position).getUserInfo().getUuid(),
                                sortedList.get(position).getUserInfo().getName(), Uri.parse(sortedList.get(position).getUserInfo().getAvatar()));
                        RongMentionManager.getInstance().mentionMember(userInfo);
                        finish();
                        return;
                    }
                    Toast.makeText(SeekContactsActivity.this, "不能@自己", Toast.LENGTH_SHORT).show();
                }
            });
            return;
        }
    }

    /**
     * 初始化所有群成员
     */
    private void initAllGroup() {
        if (GroupMainPageActivity.ALL_GROUP.equals(action)) {
            mTitleBar.setTitle("");
            String groupMembers = getIntent().getStringExtra("groupMembers");
            if (!TextUtils.isEmpty(groupMembers)) {
                list = getAvatarList(groupMembers);
                sortedList = filledData(list);
                Collections.sort(sortedList, pinyinComparator);
                adapter.updateListView(sortedList);
            }
            status = false;
            listItemClick();
            return;
        }
    }

    /**
     * 初始化发送邮件选择人
     */
    private void initSendMail() {
        if ("com.yunshipei.FROM_K9_MAIL".equals(action)) {
            mTitleBar.setTitle("选择收件人");
            sortListView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String email = getSelectedUserInfo(position).getEmail();
                    String name = getSelectedUserInfo(position).getName();
                    Intent intent = new Intent();
                    intent.putExtra(EMAIL_ADDRESS_EXTRA, email);
                    intent.putExtra(EMAIL_NAME_EXTRA, name);
                    intent.putExtra(EMAIL_FIRST_ITEM, firstItemPosition);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            });
            sortListView.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                    firstItemPosition = firstVisibleItem;
                }
            });
            return;
        }
    }

    /**
     * 修改一下
     *
     * @param position
     * @return
     */
    private UserInfo getSelectedUserInfo(int position) {
        UserInfo info;
        if (!status) {
            info = sortedList.get(position).getUserInfo();
        } else {
            info = SourceDateList.get(position).getUserInfo();
        }
        return info;
    }

    private List<SortModel> filledData(List<UserInfo> listA) {
        List<SortModel> mSortList = new ArrayList<SortModel>();
        int length = listA.size();
        for (int i = 0; i < length; i++) {
            SortModel sortModel = new SortModel();
            sortModel.setUserInfo(listA.get(i));
            // 汉字转换成拼音
            String pinyin = characterParser.getSelling(listA.get(i).getName());
            String sortString = pinyin.substring(0, 1).toUpperCase();
            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }
            mSortList.add(sortModel);
        }
        return mSortList;
    }

    private boolean compare(String str1, String str2) {
        str1 = str1.toUpperCase();
        str2 = str2.toUpperCase();
        if (str1.indexOf(str2.toString()) != -1 || characterParser.getSelling(str1).startsWith(str2.toString())) {
            return true;
        }
        return false;
    }

    private boolean verdictSame(List<SortModel> list, SortModel b) {
        int size = list.size();
        for (int i = 0; i < size; i++) {
            if (list.get(i).getUserInfo().getUuid().equals(b.getUserInfo().getUuid())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onClick() {
        setResult(ShareActivity.RESPONSE_CODE);
        this.finish();
        Toast.makeText(this, "已发送", Toast.LENGTH_SHORT).show();
    }

    private class SearchTask extends AsyncTask<String, Void, List<SortModel>> {
        @Override
        protected List<SortModel> doInBackground(String... params) {
            String searchKey = params[0];
            List<SortModel> filterDateList1 = new ArrayList<SortModel>();
            status = false;
            if (TextUtils.isEmpty(searchKey)) {
                status = true;
                if (GroupMainPageActivity.ALL_GROUP.equals(action)||Globals.AT.equals(action))
                {
                    filterDateList1 = sortedList;
                }else{
                    filterDateList1 = SourceDateList;
                }
            } else {
                filterDateList1.clear();
                if (GroupMainPageActivity.ALL_GROUP.equals(action)||Globals.AT.equals(action))
                {
                    for (SortModel sortModel : sortedList) {
                        String name = sortModel.getUserInfo().getName();
                        String position = sortModel.getUserInfo().getPosition();
                        String phone = sortModel.getUserInfo().getTel();
                        String department = sortModel.getUserInfo().getDepartment();
                        if (characterParser.getInSelling(name).toLowerCase().contains(searchKey.toString().toLowerCase())
                                || characterParser.getSelling(name).toLowerCase().indexOf(searchKey.toString().toLowerCase()) != -1
                                || compare(name, searchKey.toString()) || compare(position, searchKey.toString())
                                || compare(phone, searchKey.toString()) || compare(department, searchKey.toString())) {
                            if (!verdictSame(filterDateList1, sortModel)) {
                                filterDateList1.add(sortModel);
                            }
                        }
                    }
                }else{
                    for (SortModel sortModel : SourceDateList) {
                        String name = sortModel.getUserInfo().getName();
                        String position = sortModel.getUserInfo().getPosition();
                        String phone = sortModel.getUserInfo().getTel();
                        String department = sortModel.getUserInfo().getDepartment();
                        if (characterParser.getInSelling(name).toLowerCase().contains(searchKey.toString().toLowerCase())
                                || characterParser.getSelling(name).toLowerCase().indexOf(searchKey.toString().toLowerCase()) != -1
                                || compare(name, searchKey.toString()) || compare(position, searchKey.toString())
                                || compare(phone, searchKey.toString()) || compare(department, searchKey.toString())) {
                            if (!verdictSame(filterDateList1, sortModel)) {
                                filterDateList1.add(sortModel);
                            }
                        }
                    }
                }
            }
            return filterDateList1;
        }

        @Override
        protected void onPostExecute(List<SortModel> filterDateList1) {
            // 根据a-z进行排序
            Collections.sort(filterDateList1, pinyinComparator);
            sortedList.clear();
            sortedList.addAll(filterDateList1);
            adapter.updateListView(filterDateList1);
        }
    }

    /**
     * 获取群组成员列表
     *
     * @param originalStr
     * @return
     */
    public List<UserInfo> getAvatarList(String originalStr) {
        List<UserInfo> list = new ArrayList<>();
        try {
            JSONArray groupMemIdArray = new JSONArray(originalStr);
            int length = groupMemIdArray.length();
            for (int i = 0; i < length; i++) {
                UserInfo userInfo = dbUtil.queryUserInfoByid(groupMemIdArray.getString(i));
                if (userInfo != null) {
                    list.add(userInfo);
                } else {
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    public void listItemClick() {
        sortListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("userInfo", getSelectedUserInfo(position));
                intent.putExtras(bundle);
                intent.setClass(SeekContactsActivity.this, DetailContactsActivity.class);
                startActivity(intent);
            }
        });
    }

    private List<UserInfo> removeUserIsAdmin(List<UserInfo> list) {
        Iterator<UserInfo> iterator = list.iterator();
        while (iterator.hasNext()) {
            if (Boolean.parseBoolean(iterator.next().getIsAdmin())) {
                iterator.remove();
            }
        }
        return list;
    }
}
